package com.lecoboy.highconcurrency.concurrent_tools;

import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 银行流水处理服务类
 */
public class BankWaterService {
    /**
     * 创建4个屏障，处理完之后执行当前类的run方法
     */
    private CyclicBarrier c = new CyclicBarrier(4, new JoinAllResult());

    /**
     * 假设只有4个sheet，所以启动4个线程
     */
    private Executor executor = Executors.newFixedThreadPool(4);
    /**
     * 保存4个sheet计算出的银行流水结果
     */
    private ConcurrentHashMap<String, Integer> sheetBankWaterCount = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        BankWaterService bankWaterService = new BankWaterService();
        bankWaterService.count();
    }
    private void reset(){
        c.reset();
    }

    private void count() {
        for (int i = 0; i < 4; i++) {
            int count=0;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    //计算当前sheet的银行流水数据
                    int water = 10;
                    sheetBankWaterCount.put(Thread.currentThread().getName(), water);
                    try {

                        //银行计算完成，插入一个屏障
                        c.await();
                        System.out.println(Thread.currentThread().getName() + "到达屏障");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    class JoinAllResult implements Runnable {
        int result = 0;

        @Override
        public void run() {
            System.out.println("----开始执行计算sum----");
            //汇总每个sheet计算出的结果
            for (Map.Entry<String, Integer> sheet : sheetBankWaterCount.entrySet()) {
                result += sheet.getValue();
            }
            //输出结果
            sheetBankWaterCount.put("result", result);
            System.out.println("sheet总和：" + result);
        }
    }
}
